package cn.gwm.flink.streaming.strategy.vehiclepredict;

import cn.gwm.flink.streaming.constant.ChargePredictFields;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.flink.api.common.state.MapState;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * @author : GW00280745
 * @date : 2022/11/30 17:45
 * @description :
 */
public class RocksData {
    private volatile static RocksData instance;
    public static RocksData obj() {
        if (instance == null) {
            synchronized (RocksData.class) {
                if (instance == null) {
                    instance = new RocksData();
                }
            }
        }
        return instance;
    }

    public String getRocksValNoDefault(MapState<String, Map> mapTempAvgState, String hashKey, String fieldKey){
        if (StringUtils.isBlank(hashKey) || StringUtils.isBlank(fieldKey)){
            return null;
        }
        try {
            Map map = mapTempAvgState.get(hashKey);
            if (map==null){
                return null;
            }
            Object o = map.get(fieldKey);
            if (o == null){
                return null;
            }
            return o.toString();
        }catch (Exception je){
            je.printStackTrace();
        }
        return null;
    }


    /**
     * @description: 温升速率读取规则： 车型+加热+axis+vin > 车型+无加热+axis+vin > 车型+加热+axis+another vin > 车型+无加热+axis+another vin > axis + anyone vin
     *
     * @author:  GW00280745
     * @date: 2022/7/5 8:18
     * @param:
     * @param: jedis
     * @param: hashKey
     * @param: fieldKey
     * @return:
     * @return: java.lang.String
     **/
    public String getRocksValTemp(MapState<String, Map> mapTempAvgState, String hashKey, String fieldKey) {
        if (StringUtils.isBlank(hashKey) || StringUtils.isBlank(fieldKey)){
            return null;
        }
        try {
            Map map = mapTempAvgState.get(hashKey);
            if (map==null){
                return null;
            }
            Object o = map.get(fieldKey);
            if (o != null){
                return o.toString();
            }
            //查询顺序1. bms:charge_end_temp:tempAcc:vehicleType#batterType#non_heat_cool#(温度范围,电流范围)
            String axis = StringUtils.substringAfterLast(hashKey, ChargePredictFields.ins().colon);
            String[] axisSp = axis.split(ChargePredictFields.ins().char3);
            String newAxis = axisSp[0].concat(ChargePredictFields.ins().char3)
                    .concat(axisSp[1]).concat(ChargePredictFields.ins().char3)
//                .concat("non_heat_cool").concat(EndTempConstant.char3)
                    .concat("2").concat(ChargePredictFields.ins().char3)
                    .concat(axisSp[3]).concat(ChargePredictFields.ins().char3);
            String newHashKey = ChargePredictFields.ins().redisNameSpaceTemp.concat(newAxis);
            //查询顺序2. 车型+无加热+axis+vin
//        if (!StringUtils.equalsIgnoreCase(axisSP[2],"non_heat_cool")){
            if (!StringUtils.equalsIgnoreCase(axisSp[DwsStrConstant.ins().num2],DwsStrConstant.ins().num2Str)){
                String newFieldKey = hkeysOne(mapTempAvgState, newHashKey, fieldKey, false);
                if (StringUtils.isNotBlank(newFieldKey)){
//                String s = hsetVal(jedis, newHashKey, newFieldKey)
                    String s = getRocksValNoDefault(mapTempAvgState,newHashKey, newFieldKey);
                    if (StringUtils.isNotBlank(s)){
                        return s;
                    }
                }
            }
            //查询顺序3. 车型+加热+axis+another vin
            String anotherFieldKey = hkeysOne(mapTempAvgState, hashKey, fieldKey, true);
            if (StringUtils.isNotBlank(anotherFieldKey)){
//            String s = hsetVal(jedis, hashKey, anotherFieldKey)
                String s = getRocksValNoDefault(mapTempAvgState,hashKey, anotherFieldKey);
                if (StringUtils.isNotBlank(s)){
                    return s;
                }
            }
            //查询顺序4. 车型+无加热+axis+another vin
//        if (!StringUtils.equalsIgnoreCase(axisSP[2],"non_heat_cool")){
            if (!StringUtils.equalsIgnoreCase(axisSp[DwsStrConstant.ins().num2],DwsStrConstant.ins().num2Str)){
                String newFieldKey = hkeysOne(mapTempAvgState, newHashKey, anotherFieldKey, false);
                if (StringUtils.isNotBlank(newFieldKey)){
//                String s = hsetVal(jedis, newHashKey, newFieldKey)
                    String s = getRocksValNoDefault(mapTempAvgState,newHashKey, newFieldKey);
                    if (StringUtils.isNotBlank(s)){
                        return s;
                    }
                }
            }
//        //查询顺序5. axis + anyone vin
//        String defaultHashKey  EndTempConstant.redisNameSpace_temp.concat(axis)
//        String defaultFieldKey = hkeysOne(jedis, defaultHashKey, anotherFieldKey, false)
//        if (StringUtils.isNotBlank(defaultFieldKey)){
//            String s = hsetVal(jedis, defaultHashKey, defaultFieldKey)
//            if (StringUtils.isNotBlank(s)){
//                return s
//            }
//        }
        }catch (Exception e){
           e.printStackTrace();
        }
        return ChargePredictFields.ins().blankStr;
    }
    private String hkeysOne(MapState<String, Map> mapTempAvgState, String hashKey, String fieldKey,boolean isDiff){
        try {
            Map map = mapTempAvgState.get(hashKey);
            if (map==null){
                return null;
            }
            Iterator iterator = map.entrySet().iterator();
            while (iterator.hasNext()){
                String hkey = iterator.next().toString();
                if (StringUtils.isBlank(hkey)){
                    continue;
                }
                if ( isDiff && StringUtils.equalsIgnoreCase(fieldKey,hkey)){
                    continue;
                }
                return hkey;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }


    public void redis2Rocks(JedisCluster jedisCluster,MapState<String, Map> mapTempAvgState){
        fromRedis2Rocks(jedisCluster, mapTempAvgState,"dcp:");
    }

    private void fromRedis2Rocks(JedisCluster jedisCluster, MapState<String, Map> mapTempAvgState,String keyPattern) {
        Set<String> batterKeys = redisKeys(jedisCluster,keyPattern);
        data2Rocks(jedisCluster, mapTempAvgState, batterKeys);
    }

    private void data2Rocks(JedisCluster jedisCluster, MapState<String, Map> mapTempAvgState, Set<String> batterKeys) {
        for (String batterKey : batterKeys) {
            try {
                Map map = mapTempAvgState.get(batterKey);
                if (map==null){
                    map=new JSONObject();
                }
                Map<String, String> hMap = jedisCluster.hgetAll(batterKey);
                map.putAll(hMap);
                mapTempAvgState.put(batterKey,map);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    public Set<String> redisKeys(JedisCluster jedisCluster,String keyPattern){
        Set<String> keys = new HashSet<>();
        Map<String, JedisPool> nodes = jedisCluster.getClusterNodes();
        for(Iterator<JedisPool> it=nodes.values().iterator();it.hasNext();) {
            JedisPool pool = it.next();
            Jedis jedis = pool.getResource();
            try {
                Set<String> set = jedis.keys(keyPattern.concat("*"));
                keys.addAll(set);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                jedis.close();
            }
        }
        return keys;
    }
}
